import React, { useEffect, useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import HandleRecord from './HandleRecord';
import OrderInfo from './OrderInfo';
import Customer from './Customer';
import GoodsInfo from './GoodsInfo';
import OptRecord from './OptRecord';
import { getShopOrderDetail, getAfterSaleHandleByOrderId } from '@/services/shop/api';
import './style.less';
import { showMsg } from '@/utils/utils';
import { history } from 'umi';
import BreadcrumbDept from '@/components/BreadcrumbDept';
interface DetailProps {
  location?: any;
}

const Detail: React.FC<DetailProps> = (props) => {
  const { location } = props;
  const { query } = location;
  const { order_id } = query;
  const [detail, setDetail] = useState<SHOPAPI.ShopOrder>({} as SHOPAPI.ShopOrder)
  const [handleDetail, setHandleDetail] = useState<any>(null)
  const optRecordRef = useRef();

  /**
   * 订单详情
   */
  const fetchOrderDetail = async () => {
    try {
      const data = await getShopOrderDetail(order_id)
      setDetail(data)
    } catch (error) {
      showMsg(error?.data?.errmsg)
    }
  }

  /**
   * 售后记录
   */
   const fetchOrderHandleDetail = async () => {
    try {
      const data = await getAfterSaleHandleByOrderId(order_id)
      setHandleDetail(data)
    } catch (error) {
      showMsg(error?.data?.errmsg)
    }
  }

  useEffect(() => {
    if (order_id) {
      fetchOrderDetail()
      fetchOrderHandleDetail()
    }
  }, [order_id])
  
  return (
    <PageContainer title="订单详情" extra={[
      <BreadcrumbDept />
     ]} breadcrumb={{}} onBack={() => history.replace({
       pathname: '/shop/order',
       query: {
         from: 'detail'
       }
     })}>
      <OrderInfo detail={detail} optCallback={fetchOrderDetail} />

      <Customer
        detail={detail} 
        handleDetail={handleDetail}
        optCallback={() => {
          fetchOrderDetail()
          optRecordRef.current.reload();
        }} />
     
      <GoodsInfo 
        goodsList={detail.order_goods_list} 
        title={'3. 订单商品信息'} /> 

      {
        handleDetail && <HandleRecord orderdetail={detail} detail={handleDetail} title={detail.ship_method === 'Z' ? "3. 售后处理记录" : '4. 售后处理记录'} />
      }
      
      <OptRecord 
        ref={optRecordRef}
        order_id={order_id} 
        title={handleDetail ? '5. 操作记录' : '4. 操作记录'} />
    </PageContainer>
  );
};
export default Detail;
